
/* Generated by Interface Builder */

#import "UncompressApp.h"
#import <stdio.h>
#import <string.h>
#import <appkit/Form.h>
#import <appkit/Panel.h>
#import <appkit/Text.h>
#import <appkit/OpenPanel.h>

@implementation UncompressApp

- appDidInit:sender
{
    openPanel = [OpenPanel new]; 
    [openPanel allowMultipleFiles:YES]; 
    mode = NO;
    [nameWindow selectTextAt:0];
    [[nameWindow window] makeKeyWindow];
    return self;
}

- setMode:sender
{
    mode = [sender intValue];
    [nameWindow  selectTextAt:0];
    return self;
}

- setNameWindow:anObject
{
    nameWindow = anObject;
    return self;
}

- go:sender
{
    const char *fname;
    id textObj;
    int end, errnum;
    char command[BUFSIZ], tmpbuf[3];
    int system();

    fname = [nameWindow stringValueAt:0];
    [nameWindow  selectTextAt:0];
    textObj = [nameWindow currentEditor];
    end = [textObj textLength];

    // Select Uncompress or Compress Command and fix string in nameWindow
    [textObj getSubstring:tmpbuf start:end-2 length:2];
    if (mode == NO) {
	strcpy(command,"/usr/ucb/uncompress ");
	if (strncmp(tmpbuf,".Z",2)) {
	    NXRunAlertPanel("Uncompress","File is not in compressed format", NULL, NULL, NULL);
	    return nil;
	}
	[textObj setSel:end-2 :end];
	[textObj delete:nil];
    }
    else {
	strcpy(command,"/usr/ucb/compress ");
	if ( strncmp(tmpbuf,".Z",2) ) {
	    [textObj setSel:end :end];
	    [textObj replaceSel:".Z"];
	} else {
	    NXRunAlertPanel("Compress","File is already compressed", NULL, NULL, NULL);
	    return nil;
	}
    }

    // Execute command
    strcat(command,fname);
    if (errnum = system(command)) {
	char *errorString = strerror(errnum);
	NXRunAlertPanel("Uncompress","Didn't work! - %s", NULL, NULL, NULL,errorString);
	return nil;
    }

    return self;
}

- (BOOL)appAcceptsAnotherFile:sender
{
    return YES;
}

- (int)appOpenFile:(const char *)fileName type:(const char *)aType
{
    [nameWindow setStringValue:fileName at:0];
    [nameWindow selectTextAt:0];
    return YES;
    //[self go:nil];
}

- setFile:sender
{
    const char *directory;
    const char *const *files;
    char path[BUFSIZ];
    static const char *const dataType[2] = {"Z", NULL};

    if ([openPanel runModalForTypes:(mode==NO)?dataType:NULL]) {
	files = [openPanel filenames];
	directory = [openPanel directory];
    }
    else return nil;

    if (directory && *directory && files && *files) {
	const char *const *ptr;
	for(ptr = files; *ptr; ptr++) {
	    strcat(path, directory);
	    strcat(path, "/");
	    strcat(path, *ptr);
	    strcat(path," ");
	}
	path[strlen(path)-1] = 0;
	[nameWindow setStringValue:path at:0];
	[nameWindow selectTextAt:0];
    } else {
	NXRunAlertPanel("Uncompress","Null file name",NULL,NULL,NULL);
	return nil;
    }
    return self;
}

@end
